﻿<template>
	<div class="etQuestionCate-container">
		<el-dialog v-model="isShowDialog" :width="800" draggable="" :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<!--<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>-->
					<span>{{ props.title }}</span>
				</div>
			</template>
			<el-form :model="ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="父级分类">
							<el-cascader
								v-model="ruleForm.parentId"
								:options="parentCateOptions"
								:props="{
									checkStrictly: true,
									value: 'id',
									label: 'name',
									emitPath: false,
									disabled: 'disabled'
								}"
								placeholder="请选择父级分类"
								clearable
								filterable
								:filter-method="filterParentNode"
							>
								<template #default="{ node, data }">
									<span>{{ data.name }}</span>
									<span v-if="!node.isLeaf">({{ data.children?.length || 0 }})</span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="名称" prop="name">
							<el-input v-model="ruleForm.name" placeholder="请输入名称" maxlength="128" show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="排序" prop="orderNo">
							<el-input-number v-model="ruleForm.orderNo" :min="0" :max="9999" placeholder="请输入排序" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="描述" prop="description">
							<el-input
								v-model="ruleForm.description"
								type="textarea"
								:rows="4"
								placeholder="请输入描述"
								maxlength="512"
								show-word-limit
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="状态" prop="status">
							<el-switch
								v-model="ruleForm.status"
								:active-value="1"
								:inactive-value="0"
								active-text="启用"
								inactive-text="禁用"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-input),
:deep(.el-cascader),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
	import { ref,onMounted } from "vue";
	import { ElMessage } from "element-plus";
	import type { FormRules } from "element-plus";
  	import { formatDate } from '/@/utils/formatTime';
	import { addEtQuestionCate, updateEtQuestionCate, detailEtQuestionCate, getEtQuestionCateTree } from "/@/api/main/et-question-cate";

	//父级传递来的参数
	var props = defineProps({
		title: {
		type: String,
		default: "",
	},
	});
	//父级传递来的函数，用于回调
	const emit = defineEmits(["handleQuery"]);
	const ruleFormRef = ref();
	const isShowDialog = ref(false);
	const parentCateOptions = ref<any[]>([]);
	const currentId = ref<number>();
	const ruleForm = ref<any>({
		status: 1,
		orderNo: 100,
	});
	//自行添加其他规则
	const rules = ref<FormRules>({
		name: [
			{ required: true, message: '请输入分类名称', trigger: 'blur' },
			{ min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
		],
		orderNo: [
			{ required: true, message: '请输入排序号', trigger: 'blur' },
			{ type: 'number', message: '排序号必须为数字', trigger: 'blur' }
		],
		questionBankId: [
			{ required: true, message: '题库ID不能为空', trigger: 'blur' }
		]
	});

	// 过滤父级分类选项
	const filterParentNode = (value: string, data: any) => {
		if (!value) return true;
		return data.name.toLowerCase().includes(value.toLowerCase());
	};

	// 处理父级分类选项
	// 定义函数并指定返回类型
	const processParentOptions = (data: any[], currentId: number): any[] => {
		return data.map(item => {
			// 禁用当前节点及其子节点
			const isDisabled = item.id === currentId || isChildNode(item, currentId);
			return {
				...item,
				disabled: isDisabled,
				children: item.children ? processParentOptions(item.children, currentId) : []
			};
		});
	};

	// 检查是否为子节点
	const isChildNode = (node: any, targetId: number): boolean => {
		if (!node.children) return false;
		return node.children.some((child: any) => 
			child.id === targetId || isChildNode(child, targetId)
		);
	};

	// 加载父级分类选项
	const loadParentOptions = async (questionBankId: number) => {
		try {
			const res = await getEtQuestionCateTree(questionBankId);
			const treeData = res.data.result || [];
			parentCateOptions.value = processParentOptions(treeData, currentId.value || 0);
		} catch (error) {
			console.error('加载父级分类失败:', error);
			ElMessage.error('加载父级分类失败');
		}
	};

	// 页面加载时
	onMounted(() => {

	});

	// 打开弹窗
	const openDialog = async (row: any) => {
		currentId.value = row.id;
		await loadParentOptions(row.questionBankId);
		
		if (row.id) {
			const res = await detailEtQuestionCate(row.id);
			ruleForm.value = res.data.result;
		} else {
			ruleForm.value = { status: 1, orderNo: 100, ...row };
		}
		isShowDialog.value = true;
	};

	// 关闭弹窗
	const closeDialog = () => {
		emit("handleQuery");
		isShowDialog.value = false;
	};

	// 取消
	const cancel = () => {
		isShowDialog.value = false;
	};

	// 提交
	const submit = async () => {
		if (!ruleFormRef.value) return;
		await ruleFormRef.value.validate(async (valid: boolean) => {
			if (!valid) return;
			try {
				if (ruleForm.value.id) {
					await updateEtQuestionCate(ruleForm.value);
				} else {
					await addEtQuestionCate(ruleForm.value);
				}
				ElMessage.success('保存成功');
				closeDialog();
			} catch (error: any) {
				console.error('保存失败:', error);
				ElMessage.error(error.message || '保存失败');
			}
		});
	};

	//将属性或者函数暴露给父组件
	defineExpose({ openDialog });
</script>




